<template>
  <div class="outbox">
    <h2>
      学校部门信息 &nbsp;
      <el-button type="primary" icon="el-icon-plus" @click="openAddDialog"
        >添加</el-button
      >
    </h2>

    <div
      class="department-info"
      v-for="department in departments"
      :key="department.id"
    >
      <el-descriptions
        class="margin-top"
        :title="department.name"
        :column="3"
        :size="size"
        border
      >
        <template slot="extra">
          <el-button size="small" @click.stop="openChangeDialog(department)"
            >修改</el-button
          >
        </template>
        <template slot="extra">
          <el-button
            type="danger"
            size="small"
            @click.stop="deleteDepartment(department.id)"
            >删除</el-button
          >
        </template>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            部门名
          </template>
          {{ department.name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            联系电话
          </template>
          {{ department.phone }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-location-outline"></i>
            办公地点
          </template>
          {{ department.address }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-time"></i>
            办公时间
          </template>
          {{ department.officeHours }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-chat-line-square"></i>
            邮箱地址
          </template>
          {{ department.email }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="tablePage.pageNum"
        :page-size="tablePage.pageSize"
        :page-sizes="pageSizes"
        :total="tablePage.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="showChangeDialog"
      width="50%"
      @close="closeChangeDialog"
    >
      <!-- 修改部门信息的表单 -->
      <el-form :model="changeFormData" ref="changeForm" label-width="80px">
        <el-form-item label="部门名" prop="name">
          <el-input v-model="changeFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="changeFormData.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="changeFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="办公时间" prop="officeHours">
          <el-input v-model="changeFormData.officeHours"></el-input>
        </el-form-item>
        <el-form-item label="办公地点" prop="address">
          <el-input v-model="changeFormData.address"></el-input>
        </el-form-item>
      </el-form>

      <!-- 修改/添加部门信息的按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeChangeDialog">取消</el-button>
        <el-button type="primary" @click="handleDialogAction">{{
          dialogAction
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    // this.fetchSchoolDepartment();
    this.fetchData();
  },
  computed: {
    dialogTitle() {
      return this.changeFormData.id ? "修改部门信息" : "添加部门信息";
    },
    dialogAction() {
      return this.changeFormData.id ? "修改" : "添加";
    },
  },
  data() {
    return {
      departments: [],
      showChangeDialog: false,
      changeFormData: {
        id: null,
        name: "",
        phone: "",
        email: "",
        officeHours: "",
        address: "",
      },
      size: "",
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 5, // 每页多少条
        total: 0, // 总记录数
      },
      pageSizes: [5, 10, 20, 30],
    };
  },
  methods: {
    fetchData() {
      const { pageNum, pageSize } = this.tablePage;
      // 发送分页请求到后端
      // 你可以使用 axios 或其他 HTTP 请求库
      // 在请求参数中包括页码和每页条数
      // 例如，使用 axios 发送 GET 请求：
      this.$http
        .get(`/departments/page?pageNum=${pageNum}&pageSize=${pageSize}`)
        .then((response) => {
          // 处理后端返回的分页数据
          const { records, total } = response.data;
          this.departments = records.map(
            (department) => ({
            id: department.depId,
            name: department.depName,
            phone: department.depPhone,
            email: department.depEmail,
            officeHours: department.depTime,
            address: department.depAddress,
          })
          ); // 更新部门数据
          this.tablePage.total = total; // 更新总记录数
        })
        .catch((error) => {
          console.error("Error fetching departments:", error);
        });
    },
    // 打开添加部门对话框
    openAddDialog() {
      // 清空添加部门表单数据
      this.changeFormData.id = null;
      this.changeFormData.name = "";
      this.changeFormData.phone = "";
      this.changeFormData.email = "";
      this.changeFormData.officeHours = "";
      this.changeFormData.address = "";
      this.showChangeDialog = true; // 打开修改对话框
    },

    // 打开修改对话框，并传递部门数据
    openChangeDialog(department) {
      this.changeFormData.id = department.id; // 设置要修改的部门的 ID
      this.changeFormData.name = department.name;
      this.changeFormData.phone = department.phone;
      this.changeFormData.email = department.email;
      this.changeFormData.officeHours = department.officeHours;
      this.changeFormData.address = department.address;
      this.showChangeDialog = true; // 打开修改对话框
    },

    // 关闭修改对话框
    closeChangeDialog() {
      this.showChangeDialog = false;
      // 清空修改数据
      this.changeFormData.name = "";
      this.changeFormData.phone = "";
      this.changeFormData.email = "";
      this.changeFormData.officeHours = "";
      this.changeFormData.address = "";
      this.changeFormData.id = null;
    },
    // 处理修改/添加部门信息的按钮点击事件
    handleDialogAction() {
      if (this.changeFormData.id) {
        // 执行修改部门信息的逻辑
        this.updateDepartment();
      } else {
        // 执行添加部门信息的逻辑
        this.addDepartment();
      }
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage;
      // 在此刷新数据
      this.fetchData();
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      // 在此刷新数据
      this.fetchData();
    },
    // fetchSchoolDepartment() {
    //   // 获取学校部门信息
    //   this.$http
    //     .get("/departments/all")
    //     .then((response) => {
    //       this.departments = response.data.map((department) => ({
    //         id: department.depId,
    //         name: department.depName,
    //         phone: department.depPhone,
    //         email: department.depEmail,
    //         officeHours: department.depTime,
    //         address: department.depAddress,
    //       }));
    //     })
    //     .catch((error) => {
    //       console.error("Error fetching departments:", error);
    //     });
    // },
    // 保存新添加的部门信息
    addDepartment() {
      // 构建新部门的数据对象
      const newDepartment = {
        depName: this.changeFormData.name,
        depPhone: this.changeFormData.phone,
        depEmail: this.changeFormData.email,
        depTime: this.changeFormData.officeHours,
        depAddress: this.changeFormData.address,
      };

      // 发送添加部门的请求
      this.$http
        .post(`/departments/add`, newDepartment)
        .then((response) => {
          // 处理成功响应，可以刷新部门列表等操作
          this.$message.success("添加成功");
          // this.fetchSchoolDepartment(); // 刷新部门列表
          this.fetchData();
          this.closeChangeDialog(); // 关闭添加部门对话框
        })
        .catch((error) => {
          console.error("Error adding department:", error);
          this.$message.error('添加部门失败,该部门已存在')
        });
    },
    // 保存修改后的部门信息
    updateDepartment() {
      // 发送修改请求，根据 this.changeFormData.id 来标识要修改的部门
      const updatedDepartment = {
        depId: this.changeFormData.id,
        depName: this.changeFormData.name,
        depPhone: this.changeFormData.phone,
        depEmail: this.changeFormData.email,
        depTime: this.changeFormData.officeHours,
        depAddress: this.changeFormData.address,
      };

      // 发送请求，更新部门信息
      this.$http
        .put(`/departments/update`, updatedDepartment)
        .then((response) => {
          // 处理成功响应，可以刷新部门列表等操作
          // 关闭修改对话框
          this.closeChangeDialog();
          this.$message.success("更新成功");
          // this.fetchSchoolDepartment();
          this.fetchData();
        })
        .catch((error) => {
          console.error("Error updating department:", error);
        });
    },
    // 删除部门
    deleteDepartment(depId) {
      // 发送删除请求，根据 depId 来标识要删除的部门
      this.$http
        .delete(`/departments/delete/${depId}`)
        .then((response) => {
          // 处理成功响应，可以刷新部门列表等操作
          this.$message.success("删除成功");
          // this.fetchSchoolDepartment();
          this.fetchData();
        })
        .catch((error) => {
          console.error("Error deleting department:", error);
        });
    },
  },
};
</script>
<style scoped>
h2 {
  display: flex;
  justify-content: space-between;
}
.department-info {
  box-shadow: 0 0 20px gainsboro;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}
.outbox {
  margin: 20px;
}
.pagination {
  margin-top: 30px;
  text-align: center;
}
</style>